﻿using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Linq;
using UMC.Wiki.Entities;
using UMC.Web;
using UMC.Net;

namespace UMC.Wiki.Activities
{
    class SubjectExportActivity : WebActivity
    {
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var key = this.AsyncDialog("Key", r =>
            {
                this.Prompt("请输入项目代码");
            });
            var project = DataFactory.Instance().Project(key);
            if (project == null)
            {
                this.Prompt("无此项目");
            }
            var user = this.Context.Token.Identity();
            var member = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);

            if (member != null)
            {
                switch (member.AuthType)
                {
                    case WebAuthType.Admin:
                    case WebAuthType.User:
                        break;
                    default:
                        this.Prompt("您未有导出文档的权限");
                        break;
                }

            }
            else
            {
                this.Prompt("您未有导出文档的权限");
            }
            var temp = Path.GetTempFileName();
            var file = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", temp));

            using (var stream = Utility.Writer(file, false))
            {

                var writer = new System.IO.StreamWriter(stream);

                Export(writer, project);
                writer.Flush();
                response.Redirect(new Uri(request.Url, $"/TEMP/{temp}?file={project.Code}.json"));

            }

        }

        void Export(System.IO.TextWriter writer, Project project)
        {
            writer.Write("{");
            UMC.Data.JSON.Serialize("code", writer);
            writer.Write(":");
            UMC.Data.JSON.Serialize(project.Code, writer);
            writer.Write(",");
            UMC.Data.JSON.Serialize("title", writer);
            writer.Write(":");
            UMC.Data.JSON.Serialize(project.Caption, writer);
            writer.Write(",");

            UMC.Data.JSON.Serialize("data", writer);
            writer.Write(":[");
            var proItems = DataFactory.Instance().ProjectItem(project).OrderBy(r => r.Sequence ?? 0);
            var isItems = false;
            foreach (var m in proItems)
            {
                if (isItems)
                {
                    writer.Write(",");
                }
                else
                {
                    isItems = true;
                }
                writer.Write("{");
                UMC.Data.JSON.Serialize("code", writer);
                writer.Write(":");
                UMC.Data.JSON.Serialize(m.Code, writer);
                writer.Write(",");
                UMC.Data.JSON.Serialize("title", writer);
                writer.Write(":");
                UMC.Data.JSON.Serialize(m.Caption, writer);
                writer.Write(",");

                UMC.Data.JSON.Serialize("data", writer);
                writer.Write(":[");

                var portfolios = DataFactory.Instance().Portfolio(m).OrderBy(r => r.Sequence ?? 0);
                var isportfolios = false;
                foreach (var v in portfolios)
                {
                    if (isportfolios)
                    {
                        writer.Write(",");
                    }
                    else
                    {
                        isportfolios = true;
                    }
                    writer.Write("{");
                    UMC.Data.JSON.Serialize("title", writer);
                    writer.Write(":");
                    UMC.Data.JSON.Serialize(v.Caption, writer);
                    writer.Write(",");

                    UMC.Data.JSON.Serialize("data", writer);
                    writer.Write(":[");
                    var subs = DataFactory.Instance().Subject(v).OrderBy(r => r.Seq ?? 0);
                    var issub = false;
                    foreach (var sub in subs)
                    {
                        if (issub)
                        {
                            writer.Write(",");
                        }
                        else
                        {
                            issub = true;
                        }
                        writer.Write("{");
                        UMC.Data.JSON.Serialize("code", writer);
                        writer.Write(":");
                        UMC.Data.JSON.Serialize(sub.Code, writer);
                        writer.Write(",");
                        UMC.Data.JSON.Serialize("title", writer);
                        writer.Write(":");
                        UMC.Data.JSON.Serialize(sub.Title, writer);

                        writer.Write(",");
                        UMC.Data.JSON.Serialize("desc", writer);
                        writer.Write(":");
                        UMC.Data.JSON.Serialize(sub.Description, writer);
                        writer.Write(",");
                        UMC.Data.JSON.Serialize("content", writer);
                        writer.Write(":");
                        UMC.Data.JSON.Serialize(DataFactory.Instance().Content(sub.Id.Value)?.DataJSON, writer);
                        writer.Write("}");

                    }
                    writer.Write("]}");
                }
                writer.Write("]}");
            }
            writer.Write("]}");

        }
    }
    class SubjectUploadActivity : WebActivity
    {
        void JSON(String media_id, UMC.Security.Identity user, Project project)
        {
            var type = Utility.IntParse(this.AsyncDialog("Type", r => new UISheetDialog() { Title = "选择重名导入方式" }.Put("同名覆盖方式导入", "1").Put("同名文档不导入", "2").Put("同名重命名导入", "3")), 0);
            var content = String.Empty;

            if (media_id.StartsWith("http://") || media_id.StartsWith("https://"))
            {
                content = new Uri(media_id).WebRequest().Get(out var _);
            }
            else
            {
                media_id = Uri.UnescapeDataString(media_id);
                var filename = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", media_id.Substring(media_id.IndexOf('/', 2) + 1)));

                if (System.IO.File.Exists(filename))
                {
                    content = Utility.Reader(filename);
                }
                else
                {
                    return;
                }
            }

            var data = UMC.Data.JSON.Deserialize<Hashtable>(content);
            Array menu = data["data"] as Array;
            var total = 0;
            if (menu != null)
            {
                var now = UMC.Data.Utility.TimeID();
                foreach (var m in menu)
                {
                    var dh = m as Hashtable;

                    if (dh != null)
                    {
                        var mcode = dh["code"] as string;
                        var mtitle = dh["title"] as string;

                        var proItem = DataFactory.Instance().ProjectItem(project.Id.Value, mcode);
                        if (proItem == null)
                        {
                            proItem = new ProjectItem
                            {
                                project_id = project.Id,
                                Code = mcode,
                                Caption = mtitle,
                                Sequence = now++,
                                Id = Utility.NewId(),
                                CreationTime = DateTime.Now,
                                user_id = user.Id
                            };
                            DataFactory.Instance().Put(proItem);
                        }
                        var portfolios = DataFactory.Instance().Portfolio(proItem).ToList();

                        var ps = dh["data"] as Array;

                        foreach (var p in ps)
                        {
                            var ph = p as Hashtable;
                            var ptitle = ph["title"] as string;
                            var portfolio = portfolios.Find(r => r.Caption == ptitle);
                            if (portfolio == null)
                            {
                                portfolio = new Portfolio
                                {
                                    Caption = ptitle,
                                    Id = UMC.Data.Utility.NewId(),
                                    CreationTime = DateTime.Now,
                                    project_id = project.Id,
                                    project_item_id = proItem.Id,
                                    Sequence = now++,
                                    user_id = user.Id
                                };

                                DataFactory.Instance().Put(portfolio);
                            }
                            var subs = ph["data"] as Array;
                            foreach (var s in subs)
                            {
                                var sh = s as Hashtable;

                                var scode = sh["code"] as string;
                                var stitle = sh["title"] as string;
                                var scontent = sh["content"] as string;

                                var sub = DataFactory.Instance().Subject(project.Id.Value, proItem.Id.Value, scode);
                                if (sub == null)
                                {
                                    sub = new Subject()
                                    {
                                        CreationTime = DateTime.Now,
                                        Title = stitle,
                                        IsPicture = false,
                                        Id = Utility.NewId(),
                                        LastDate = DateTime.Now,
                                        Poster = user.Alias,
                                        Seq = now++,
                                        Code = scode,
                                        portfolio_id = portfolio.Id,
                                        project_item_id = proItem.Id,
                                        project_id = project.Id,
                                        last_user_id = user.Id,
                                        user_id = user.Id,
                                        Status = -1
                                    };
                                    total++;
                                    DataFactory.Instance().Put(sub);
                                }
                                else
                                {
                                    if (String.IsNullOrEmpty(sub.Description))
                                    {
                                        var celss = UMC.Data.JSON.Deserializes<WebMeta>((String.IsNullOrEmpty(scontent) ? "[]" : scontent)) ?? new UMC.Web.WebMeta[] { };
                                        var sb = new StringBuilder();
                                        foreach (var pom in celss)
                                        {
                                            switch (pom["type"])
                                            {
                                                case "CMSText":
                                                    var value = pom.GetMeta("value");
                                                    var format = pom.GetMeta("format")["text"];
                                                    var fValue = Utility.Format(format, value.GetDictionary(), String.Empty);
                                                    if (String.Equals(fValue, sub.Title) == false)
                                                    {
                                                        sb.Append(fValue);
                                                    }
                                                    if (sb.Length > 250)
                                                    {
                                                        break;
                                                    }

                                                    break;
                                            }
                                        }
                                        sub.Description = sb.Length > 250 ? sb.ToString(0, 250) : sb.ToString();
                                        sub.Status = 1;
                                        sub.Poster = user.Alias;
                                        sub.ReleaseTime = DateTime.Now;
                                        DataFactory.Instance().Put(sub);
                                    }
                                    if (type == 1)
                                    {
                                        sub = new Subject()
                                        {
                                            CreationTime = DateTime.Now,
                                            Title = stitle,
                                            IsPicture = false,
                                            Id = Utility.NewId(),
                                            LastDate = DateTime.Now,
                                            Poster = user.Alias,
                                            Seq = now++,
                                            Code = Utility.Parse36Encode(now),
                                            portfolio_id = portfolio.Id,
                                            project_item_id = proItem.Id,
                                            project_id = project.Id,
                                            last_user_id = user.Id,
                                            user_id = user.Id,
                                            Status = -1
                                        };
                                        total++;
                                        DataFactory.Instance().Put(sub);
                                    }
                                    else
                                    {
                                        continue;
                                    }

                                }
                                DataFactory.Instance().Put(new SubjectContent
                                {
                                    ContentType = "html",
                                    DataJSON = scontent,
                                    Id = sub.Id
                                });
                            }
                        }

                    }
                }
                var ax = DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id };
                DataFactory.Instance().Put(new Attention
                {
                    Id = user.Id,
                    SubjectTotal = (ax.SubjectTotal ?? 0) + total
                });
                DataFactory.Instance().Put(new Project
                {
                    Id = project.Id,
                    SubjectTotal = (project.SubjectTotal ?? 0) + total
                });
            }
        }
        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var sId = this.AsyncDialog("Id", "auto");
            var media_id = this.AsyncDialog("Key", g =>
            {
                return UIDialog.Create("File");
            });
            var user = this.Context.Token.Identity();
            if (user.IsAuthenticated == false)
            {
                this.Prompt("请先登录", false);
                this.Context.Send("Login", true);
            }
            var title = media_id.Substring(media_id.LastIndexOf('/') + 1);
            title = title.Substring(0, title.LastIndexOf('.'));

            var portfolioId = UMC.Data.Utility.UInt64Parse(sId, 0);
            if (portfolioId > 0)
            {


                var Portfolio = DataFactory.Instance().Portfolio(portfolioId);
                var projectItem = DataFactory.Instance().ProjectItem(Portfolio.project_item_id.Value);

                var project = DataFactory.Instance().Project(Portfolio.project_id.Value);
                var member = DataFactory.Instance().ProjectMember(project.Id.Value, user.Id.Value);

                if (member != null)
                {
                    switch (member.AuthType)
                    {
                        case WebAuthType.Admin:
                        case WebAuthType.User:
                            break;
                        default:
                            this.Prompt("您未有新增文档的权限");
                            break;
                    }

                }
                else
                {
                    this.Prompt("您未有新增文档的权限");
                }

                if (media_id.EndsWith(".json", StringComparison.CurrentCultureIgnoreCase))
                {
                    JSON(media_id, user, project);
                    this.Prompt("导入成功,请刷新");
                    return;
                }


                if (media_id.EndsWith(".md", StringComparison.CurrentCultureIgnoreCase) == false)
                {
                    this.Prompt("目前只支持md格式文件");
                }
                Array celss;
                var content = String.Empty;
                if (media_id.StartsWith("http://") || media_id.StartsWith("https://"))
                {
                    content = new Uri(media_id).WebRequest().Get(out var _);
                }
                else
                {
                    media_id = Uri.UnescapeDataString(media_id);
                    var filename = UMC.Data.Reflection.ConfigPath(String.Format("Static\\TEMP\\{0}", media_id.Substring(media_id.IndexOf('/', 2) + 1)));

                    if (System.IO.File.Exists(filename))
                    {
                        content = Utility.Reader(filename);
                    }
                    else
                    {
                        return;
                    }
                }

                var cells = Data.Markdown.Transform(content);
                var dlist = new ArrayList();
                foreach (var d in cells)
                {
                    dlist.Add(new WebMeta().Put("type", d.Type).Put("value", d.Data).Put("format", d.Formats).Put("style", d.Style).GetDictionary());

                }
                celss = dlist.ToArray();

                var sub = new Subject()
                {
                    CreationTime = DateTime.Now,
                    Title = title,
                    IsPicture = false,
                    Id = Utility.NewId(),
                    LastDate = DateTime.Now,
                    Poster = user.Alias,
                    Seq = Utility.TimeID(),
                    last_user_id = user.Id,
                    user_id = user.Id,
                    Status = -1,
                };

                sub.portfolio_id = portfolioId;
                sub.project_id = project.Id;
                sub.project_item_id = projectItem.Id;

                sub.Code = Utility.Parse36Encode(Utility.IntParse(sub.Id.Value)[1]);

                DataFactory.Instance().Put(sub);
                DataFactory.Instance().Put(new SubjectContent
                {
                    Id = sub.Id,
                    Content = content,
                    ContentType = "markdown",
                    DataJSON = Data.JSON.Serialize(celss)

                });
                DataFactory.Instance().Put(new ProjectDynamic
                {
                    Time = Utility.TimeSpan(sub.LastDate.Value),
                    user_id = user.Id,
                    Explain = "导入了文档",
                    project_id = sub.project_id,
                    Alias = user.Alias,
                    refer_id = sub.Id,
                    Title = sub.Title,
                    Type = DynamicType.Subject
                });


                var ax = DataFactory.Instance().Attention(user.Id.Value) ?? new Attention { Id = user.Id };
                DataFactory.Instance().Put(new Attention
                {
                    Id = user.Id,
                    SubjectTotal = (ax.SubjectTotal ?? 0) + 1
                });
                DataFactory.Instance().Put(new Project
                {
                    Id = project.Id,
                    SubjectTotal = (project.SubjectTotal ?? 0) + 1
                });
                var path = String.Format("{0}/{1}/{2}", project.Code, projectItem.Code, sub.Code);

                this.Context.Send(new UMC.Web.WebMeta().Put("type", "Subject.Portfolio.Import").Put("Id", Portfolio.Id).Put("Sub", sub.Id).Put("Title", sub.Title)
                    .Put("Path", path), true);
            }
        }

    }
}